from machine import Pin,SoftI2C,Timer
import dht
import time
import ssd1306
import framebuf
from wifi import upload_codemao,getTime
from localtime import timer

i2c = SoftI2C(scl=Pin(1), sda=Pin(2))
temp = -1
humidity = -1

# simple 8x8 degree symbol, 1 pixel thick line, in the upper half of character cell
p0 = bytearray([0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00])
# p1 drops symbol in cell by 1 pixel
p1 = bytearray([0x00, 0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00])  
# convert to framebuf- 
#    8,8 is size of blit- 8x8 pixels, 8 per row
#    MONO_HLSB indicated bit 7 is left most and bits are in rows
fb0 = framebuf.FrameBuffer(p0, 8, 8, framebuf.MONO_HLSB)
fb1 = framebuf.FrameBuffer(p1, 8, 8, framebuf.MONO_HLSB)

oled = None

def readDHT11():
    global temp,humidity
    time.sleep(1)
    d = dht.DHT11(Pin(4, Pin.IN))
    try:
        d.measure()
        temp = d.temperature()
        humidity = d.humidity()
        print(f"Temperature : {temp:.1f}°C")
        print(f"Humidity    : {humidity:.1f}%")
    except Exception as e:
        print(e)
    
def show_oled():
    global oled
    oled_width = 128
    oled_height = 32
    try:
        oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
        oled.text('temp: ' + str(temp), 0, 0)
        oled.blit(fb0, 65, 0)
        oled.text("C", 72, 0)
        #oled.blit(fb1, 10, 5)
        oled.text('humidity: ' + str(humidity) + "%", 0, 10)
        oled.show()
    except Exception as e:
        print(e)
        
def show_loading():
    global oled
    x = 75
    y = 20
    dot = len('send') * 5 + x - 5
    try:
        getTime()
        date_str = timer.get_time()
        print(date_str)
        h = "{:02}".format(timer.hour)
        m = "{:02}".format(timer.minute)
        s = "{:02}".format(timer.second)
        oled.text(f"{h}:{m}:{s}", 0, y)
        oled.text('send', x, y)
        oled.show()
        
        time.sleep(0.5)
        oled.text('.', dot + 15, y)
        oled.show()
        
        time.sleep(0.5)
        oled.text('.', dot + 20, y)
        oled.show()
        
        time.sleep(0.5)
        oled.text('.', dot + 26, y)
        oled.show()
        
        upload_codemao(t_str + "," + h_str)
        
        oled.rect(x, y, x + 30, y + 5, 0)
        oled.show()
        
        oled.text('ok', x, y)
        oled.show()
        time.sleep(1)
        oled.rect(x, y, x + 30, y + 5, 0)
        oled.show()
        
    except Exception as e:
        with open('log.txt', 'w') as f:
            f.write(str(e))
            machine.reset()
        

while True:
    readDHT11()
    show_oled()
    t_str = str(temp) + "°C"
    h_str = str(humidity) + "%"
    show_loading()
    time.sleep(10)


